<?php

namespace app\api\service\pay;


use app\api\model\BoxCollect;
use app\api\model\business\EntrustRecords;
use app\api\model\Order;
use app\api\model\OrderGoods;
use app\api\model\User as UserModel;
use app\api\model\user\BalanceLog as BalanceLogModel;
use app\common\enum\EntrustType;
use app\common\enum\order\OrderStatus;
use app\common\enum\order\PayStatus;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use think\facade\Db;
use think\facade\Log;

class EntrustOrderPay extends PaySuccess
{

    public function onSuccess(array $payment, int $payType): bool
    {
        Db::startTrans();
        try {
            $order = Order::where('order_no', $payment['order_no'])->find();
            // 更新订单状态
            $res = Order::update([
                'pay_status' => PayStatus::SUCCESS,
                'transaction_id' => $payment['transaction_id'],
                'order_status' => OrderStatus::COMPLETED,
                'pay_time' => time()
            ], ['order_no' => $payment['order_no']]);
            if (!$res) {
                throw new \Exception("更新订单状态失败");
            }
            $entrust_records = (new EntrustRecords())->where('id',$order->order_source_id)->find();
            $collect_ids = json_decode($entrust_records->collect_ids,true);
            //商品纳入用户盒柜--直接变更用户ID，因为之前属性不能更改
            (new BoxCollect())->update([
                'user_id' => $order->user_id,
                'entrust_status' => EntrustType::INIT
            ],[['collect_id','IN',$collect_ids]]);

            $entrust_records->status = 2;
            $entrust_records->finish_time = time();
            $entrust_records->save();

            UserModel::setIncBalance($entrust_records->user_id, $order->pay_price);
            // 新增余额变动记录
            BalanceLogModel::add(SceneEnum::ENTRUST, [
                'user_id' => $order->user_id,
                'money'   => $order->pay_price,
            ], ['order_no' => $order->order_no]);
            Db::commit();
            return true;
        }catch (\Exception $exception){
            Db::rollBack();
            Log::channel('wxpay')->info('订单号：'.$payment['order_no'].'支付失败');
            Log::channel('wxpay')->info('失败原因：'.$exception->getMessage());
            return false;
        }

    }

    public function callSuccess()
    {
        // TODO: Implement callSuccess() method.
    }
}